package com.chen.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.annotation.OptLog;
import com.chen.common.OptTypeConst;
import com.chen.common.Result;
import com.chen.common.ValidationEnum;
import com.chen.entity.User;
import com.chen.entity.Validation;
import com.chen.service.IValidationService;
import com.chen.service.impl.LoginServiceImpl;
import com.chen.vo.UserPasswordDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

/**
 * @author chenchao
 * @date 2022/7/17 18:06
 */

@RequestMapping("/sys")
@Api(value = "LoginController", tags = "系统管理")
@RestController
public class LoginController {

    @Resource
    private LoginServiceImpl loginService;

    @Autowired
    private IValidationService IValidationService;

    /**
     * info信息
     *
     * @return
     */
    @GetMapping("/info")
    @ApiOperation(value = "用户info")
    public Result info() {
        HashMap<String, Object> responseData = new HashMap<>();
//        获取当前token
        String token = StpUtil.getTokenValue();
//        获取当前用户
        int userId = StpUtil.getLoginIdAsInt();
        User user = loginService.getById(userId);

        responseData.put("token", token);
        responseData.put("role", user.getRole());
        responseData.put("name", user.getUsername());
        responseData.put("avatar", user.getAvatar());
        return Result.success(responseData);
    }


    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出")
    public Result logout() {
//        获取用户信息
        int userId = StpUtil.getLoginIdAsInt();
        //sa-token执行退出
        StpUtil.logout(userId, "PC");
        return Result.success();
    }


    /**
     * 登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result login(@RequestBody User user) {

        return loginService.login(user);
    }


    /**
     * 邮箱登录
     */
    @PostMapping("/loginEmail")
    public Result loginEmail(@RequestBody User user) {
        String email = user.getEmail();
        String code = user.getCode();
        if (StrUtil.isBlank(email)) {
            return Result.success("参数错误");
        }

        QueryWrapper<Validation> validationQueryWrapper = new QueryWrapper<Validation>();
        validationQueryWrapper.eq("email", email);
        validationQueryWrapper.eq("code", code);
        validationQueryWrapper.ge("time", new Date());
        Validation res = IValidationService.getOne(validationQueryWrapper);
        if (res == null) {
            return Result.error(400, "验证码错误");
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", email);
        User one = loginService.getOne(userQueryWrapper);
        if (one != null) {
            return Result.error(405, "该账号已注册！");
        }
        return Result.success(loginService.loginEmail(user));
    }


    @GetMapping("/sendEmail/{email}")
    public Result sendEmail(@PathVariable("email") String email) {
//        判断是否有
        Date now = new Date();
        QueryWrapper<Validation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        queryWrapper.eq("type", ValidationEnum.LOGIN.getCode());
        queryWrapper.ge("time", now);
        Validation res = IValidationService.getOne(queryWrapper);
        if (res != null) {
            return Result.error(-1, "当前您的验证码依然有效，请不要重复发送");
        }

        if (email == null) {
            return Result.error(400, "参数错误");
        }
        loginService.sendEmail(email);
        return Result.success();
    }



    /**
     * 修改密码
     * @param userPasswordDTO
     * @return
     */
    @PostMapping("/password")
    @ApiOperation(value = "修改密码")
    @OptLog(optType = OptTypeConst.UPDATE)
    public Result password(@RequestBody UserPasswordDTO userPasswordDTO) {
/*        userPasswordDTO.setPassword(SecureUtil.md5(userPasswordDTO.getPassword()));
        userPasswordDTO.setNewPassword(SecureUtil.md5(userPasswordDTO.getNewPassword()));*/
        userPasswordDTO.setPassword(userPasswordDTO.getPassword());
        userPasswordDTO.setNewPassword(userPasswordDTO.getNewPassword());
        loginService.updatePassword(userPasswordDTO);
        return Result.success();
    }


    @GetMapping("/username/{username}")
    public Result findByUsername(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return Result.success(loginService.getOne(queryWrapper));
    }
}
